package com.xzone.material.security.access

import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.MediaType
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.web.access.AccessDeniedHandler
import org.springframework.stereotype.Component

@Component
class MyAccessDeniedHandler : AccessDeniedHandler {
    override fun handle(
        request: HttpServletRequest, response: HttpServletResponse, accessDeniedException: AccessDeniedException?
    ) {
        val mapper = ObjectMapper()

        val result = HashMap<String, Any>()

        result["msg"] = "无权访问"

        response.characterEncoding = Charsets.UTF_8.name()
        response.contentType = MediaType.APPLICATION_JSON_VALUE
        response.writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result))
    }
}